<?php

declare(strict_types=1);

namespace App\Fastapp\Aspect;

use Hyperf\Di\Annotation\Aspect;
use Hyperf\Di\Aop\AbstractAspect;
use Hyperf\Di\Aop\ProceedingJoinPoint;
use Mine\Exception\NoPermissionException;
use Mine\MineRequest;
use Psr\Container\ContainerInterface;

#[Aspect]
class ApiAuthAspect extends AbstractAspect
{
    public array $annotations = [
        ApiAuth::class
    ];

    public function __construct(protected ContainerInterface $container, protected MineRequest $request)
    {
    }

    public function process(ProceedingJoinPoint $proceedingJoinPoint)
    {
        $scene = $this->request->header('app-source', 'h5');
        if (isset($proceedingJoinPoint->getAnnotationMetadata()->class[ApiAuth::class])) {
            $auth = $proceedingJoinPoint->getAnnotationMetadata()->class[ApiAuth::class];
            $codes = explode(',', $auth->code);
            if (!in_array($scene, $codes)) throw new NoPermissionException(fastapp_t('system.no_permission'));
            user($scene)->check(null, $scene);
        }

        if (isset($proceedingJoinPoint->getAnnotationMetadata()->method[ApiAuth::class])) {
            $login = $proceedingJoinPoint->getAnnotationMetadata()->method[ApiAuth::class];
            if ($login && $login->code) {
                $codes = explode(',', $login->code);
                if (!in_array($scene, $codes)) throw new NoPermissionException(fastapp_t('system.no_permission'));
                user($scene)->check(null, $scene);
            }
        }
        return $proceedingJoinPoint->process();
    }

}
